package com.gwtapps.serialization.client;

import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.Text;
import com.google.gwt.xml.client.XMLParser;

public class XMLDocument implements DocumentAdapter {

	protected class XMLDocumentObject implements DocumentObject{
		private Element element = null;
		public XMLDocumentObject(Element element) {
			this.element = element;
		}		
		
		public XMLDocumentObject() {
		}
		
		public void setAttribute( String name, String value ) {		
			Element attrElement = document.createElement( name.replace('_', '-') );
			Text text = document.createTextNode(value);
			element.appendChild(attrElement);
			attrElement.appendChild(text);	
		}					
		
		public String getAttribute( String value ) {	
			String result = "";
			NodeList list = element.getElementsByTagName(value.replace('_', '-'));
			if( list.getLength()> 0 && list.item(0).hasChildNodes() ){
				result = list.item(0).getFirstChild().getNodeValue();
			}
			return result;
		}

		public void setName( String name ){
			element = document.createElement( name );
			document.appendChild( element );	

		}
		public String getName() {
			return element.getNodeName();
		}			
	}
	
	private Document document;
	
	public XMLDocument(){		
	}
	
	public DocumentObject createObject(){
		document = XMLParser.createDocument();
		return new XMLDocumentObject();
	}	
	
	public DocumentObject[] createCollection( String name, int size ){
		document = XMLParser.createDocument();
		Element collectionElement = document.createElement( name );
		document.appendChild( collectionElement );
		DocumentObject[] objects = new DocumentObject[size];
		for( int i = 0; i<size; ++i ){
			objects[i] = new XMLDocumentObject();
		}
		return objects;
	}

	
	public String toString(){
		return document.toString();
	}
	
	public void parse( String value ){
		document = XMLParser.parse(value);
	}
	
	public DocumentObject getObject() {
		Element element = document.getDocumentElement();
		return new XMLDocumentObject( element );
	}
	
	public DocumentObject[] getCollection() {
		Element element = document.getDocumentElement();
		NodeList list = element.getChildNodes();
		int elements = 0;
		for( int i = 0; i< list.getLength(); ++i ){
			Node item = list.item(i);
			if( item instanceof Element )
				elements++;
		}
		int elementPosition = 0;
		DocumentObject[] objects = new DocumentObject[elements];
		for( int i = 0; i< list.getLength(); ++i ){
			Node item = list.item(i);
			if( item instanceof Element )
				objects[elementPosition++] = new XMLDocumentObject( (Element)item );
		}
		return objects;
	}
	public String getFormatName() {
		return "xml";
	}
}
